package org.desktop.web.server;

import static org.desktop.web.shared.constant.Constants.CLIENT_KEY;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.text.StrSubstitutor;
import org.cheetah.encrypt.Encryptor;
import org.desktop.web.client.login.service.LoginService;
import org.desktop.web.server.locator.ServiceLocator;
import org.desktop.web.server.locator.ServiceLocator.ServiceName;
import org.desktop.web.server.util.RpcUtil;
import org.desktop.web.shared.Response;
import org.json.JSONObject;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

public class LoginServiceImpl extends RemoteServiceServlet implements
		LoginService {

	private static final String urlRecoverPwd = RpcUtil.createUrlService(ServiceLocator.find(ServiceName.TIMESHEET_SERVICE),"auth/recover/${username}");
	private static final String urlRecoverPwdWithToken = RpcUtil.createUrlService(ServiceLocator.find(ServiceName.TIMESHEET_SERVICE),"auth/recover/${token}");

	@Override
	public boolean resetPassword(String login, String moduleBaseUrl)
			throws Exception {
		Map<String, String> mapper = new HashMap<String, String>();
		mapper.put("username", login);

		StrSubstitutor sub = new StrSubstitutor(mapper);
		URL _url = new URL(sub.replace(urlRecoverPwd));
		HttpURLConnection con = RpcUtil.getUrlConnection(_url, "GET");
		con.setRequestProperty("url-recover", moduleBaseUrl);
		InputStream in = con.getInputStream();
		int responseCode = con.getResponseCode();
		in.close();
		// TODO Auto-generated method stub
		return responseCode == 200;
	}

	@Override
	public Response changePassword(String newPwd, String repeatPwd,
			final String token) throws Exception {
		StrSubstitutor sub = new StrSubstitutor(new HashMap<String, String>() {
			{
				put("token", token);
			}
		});
		URL _url = new URL(sub.replace(urlRecoverPwdWithToken));
		HttpURLConnection con = RpcUtil.getUrlConnection(_url, "POST");
		con.setRequestProperty("Accept", "application/json");
		con.setRequestProperty("Content-Type", "application/octet-stream");
		OutputStream out = con.getOutputStream();
		Encryptor encryptor = new Encryptor(CLIENT_KEY);
		JSONObject obj = new JSONObject();
		obj.put("newPassword", newPwd);
		obj.put("repeatPassword", repeatPwd);

		byte[] data = encryptor.encrypt(obj.toString().getBytes());
		out.write(data);
		InputStream in = con.getInputStream();
		int code = con.getResponseCode();
		out.flush();
		out.close();
		Response response = new Response();
		response.setResponseCode(code);
		response.setSuccess(code == 200);
		String result = IOUtils.toString(in);
		response.setJsonMetadata(result);
		
		in.close();
		return response;
	}
}
